'use strict';

const Service = require('egg').Service;

module.exports = class WordFilterService extends Service {
  // Update Word Filter ///////////////////////////////////////////////////////////////////
  async updateWordFilter() {
    const helper = this.ctx.helper;
    const request = this.ctx.request;
    const connBlog = this.ctx.app.connBlog;

    // Update --------------------------------
    if (request.query.act === 'update') {
      // Set all to false then set selected ones to hidden
      await connBlog.updateSQL('blog_wordfilter', 'wf_regexp=false', 'wf_id>0');
      if (request.query.regexp) {
        const arrRegExp = request.query.regexp.split(',');
        for (let i = 0; i < arrRegExp.length; i++) {
          arrRegExp[i] = helper.checkInt(arrRegExp[i]);
        }
        await connBlog.updateSQL('blog_wordfilter', 'wf_regexp=true', 'wf_id IN (' + arrRegExp.join(',') + ')');
      }

      const arrID = request.query.id.split(',');
      const arrMode = request.query.mode.split(',');
      const arrText = request.query.text.split(',');
      const arrReplace = request.query.replace.split(',');
      for (let i = 0; i < arrID.length; i++) {
        // Check data
        arrID[i] = helper.checkInt(arrID[i]);
        arrMode[i] = helper.checkInt(arrMode[i]);
        arrText[i] = helper.trim(arrText[i]);
        arrReplace[i] = helper.trim(arrReplace[i]);
        if (arrMode[i] < 0 || arrMode[i] > 1) arrID[i] = -1;
        if (arrText[i].length < 1 || arrText[i].length > 25) arrID[i] = -1;
        if (arrMode[i] == 0 && (arrReplace[i].length < 1 || arrReplace[i].length > 50)) arrID[i] = -1;

        // Update DB
        const arrData = { wf_mode: arrMode[i],
          wf_text: arrText[i],
          wf_replace: arrReplace[i] };
        if (arrID[i] != -1) await connBlog.update('blog_wordfilter', arrData, 'wf_id=' + arrID[i]);
        // Insert new word filter
        if (arrID[i] == 0) {
          arrData.wf_regExp = !!request.query.newregexp;
          await connBlog.insert('blog_wordfilter', arrData);
        }
      }
      return;
    }

    // Delete --------------------------------
    if (request.query.act === 'delete') {
      if (!request.query.selected) return;
      let arrSelected = request.query.selected.split(',');
      for (let i = 0; i < arrSelected.length; i++) {
        arrSelected[i] = helper.checkInt(arrSelected[i]);
        if (arrSelected[i] < 1) {
          arrSelected.splice(i, 1);
          i--;
        }
      }
      if (arrSelected.length > 0) {
        arrSelected = arrSelected.join(',');
        await connBlog.doDelete('blog_wordfilter', 'wf_id IN (' + arrSelected + ')');
      }
      return;
    }

  }
};
